package com.vortex.cloud.zhsw.xinyang.util;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用于List内存分页
 *
 * @author hyh
 * @datetime 2022/12/1 10:29
 */
public class ListPageUtil implements Serializable {

    /**
     * 页码开始分页
     *
     * @param list
     * @param pageNum  页码
     * @param pageSize 每页多少条数据
     * @return
     */
    public static List startPage(List list, Integer pageNum, Integer pageSize) {
        if (list == null) {
            return null;
        }
        if (list.size() == 0) {
            return null;
        }
        //记录总数
        Integer count = list.size();
        //页数
        Integer pageCount;
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }
        //开始索引、结束索引
        int fromIndex;
        if (pageNum + 1 != pageCount.intValue()) {
            fromIndex = (pageNum) * pageSize;
        } else {
            fromIndex = (pageNum) * pageSize;
        }
        //subList方法有泄漏的风险
        List pageList = (List) list.stream().skip(fromIndex).limit(pageSize).collect(Collectors.toList());
        return pageList;
    }

    /**
     * offset开始分页
     *
     * @param list
     * @param offset 数据索引起始
     * @param limit  每页多少条数据
     * @return
     */
    public static List startPageByOffset(List list, Integer offset, Integer limit) {
        if (list == null) {
            return null;
        }
        if (list.size() == 0) {
            return list;
        }
        //subList方法有泄漏的风险
        List pageList = (List) list.stream().skip(offset).limit(limit).collect(Collectors.toList());
        return pageList;
    }
}
